import React, { useCallback, useImperativeHandle, useRef, useState } from 'react';
import DataGrid, { Column, Selection } from 'devextreme-react/data-grid';
import {
  getDataGridLookupList,
  getPeriodList,
  getZcbfInit,
  getZcbfInitializeData,
  pushZcbfInfoSQL,
} from './service';
import ProDialog from '@/pages/components/ProjectPopup';
import notify from 'devextreme/ui/notify';
import { getPeriodInfo, getUpdateZcbf } from '../../tools/service';
import SpinLoading from '../SpinLoading';
import moment from 'moment';
import { Progress } from 'antd';
import { updateZcbfPeriod } from '../../ProjectArea/NewLocalProject/service';
import { removeLocalStorageItem, getMomentMonthSjnd } from '@/utils';

const InitializePopup = React.forwardRef((props: any, ref: any) => {
  const { closeAndReload, initData } = props;
  const { popupTitle } = initData;
  const [inItVisible, setInItVisible] = useState<boolean>(false);
  const [zcbfInitData, setZcbfInitData] = useState<any>([]);
  const [TXData, setTXData] = useState<any>([]);
  const [DGMBData, setDGMBData] = useState<any>([]);
  const [TEMPLETData, setTEMPLETData] = useState<any>([]);

  const initDataGridRef = useRef<any>(0);
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [progressPercent, setProgressPercent] = useState<number>(0);
  const [xmInitType, setXmInitType] = useState<string>('');
  const [selectRowItem, setselectRowItem] = useState<string>(''); // 全选
  const [selectColItem, setselectColItem] = useState<string>(''); // 全选

  const getDataGrid = useCallback(
    async (prams: {
      TEMPLETList: string;
      CWBBTXList: string;
      mbTypeList: string;
      zcbfIDs: string;
    }) => {
      // 获取选中的组成部分信息。zcbfData
      setSpinLoad(true);
      const zcbfRes = await getZcbfInitializeData({ zcbfIDs: prams.zcbfIDs });
      if (zcbfRes.success) {
        const res = await getDataGridLookupList(prams);
        if (res.success) {
          const zcbfData: any = zcbfRes.data;
          const tempTXData = res.data[prams.CWBBTXList]?.data;
          const tempDGMBData = res.data[prams.mbTypeList]?.data.map((val: { MBMC: string }) => {
            return val.MBMC;
          });

          const tempTEMPLET = res.data[prams.TEMPLETList]?.data.map(
            (val: { tempName: string; reportType: string }) => {
              return { displayName: val.tempName, reportType: val.reportType };
            },
          );
          setTXData(tempTXData);
          setDGMBData(tempDGMBData);
          setTEMPLETData(tempTEMPLET);
          // 设置默认值
          zcbfData.forEach(
            (el: {
              TXName: any;
              HyCode: any;
              TXCode: any;
              DGMB: any;
              AuditReportTemplate: string;
              reportType: string;
            }) => {
              if (el.TXCode && el.TXName) {
                const resFindTx = tempTXData.find((item: { TXCode: string; TXName: string }) => {
                  return item.TXCode === el.TXCode && item.TXName === el.TXName;
                });
                if (!resFindTx) {
                  el.TXCode = '';
                  el.TXName = '';
                }
              } else {
                el.TXCode = tempTXData[0].TXCode;
                el.TXName = tempTXData[0].TXName;
              }
              if (el.DGMB) {
                const resFindDG = tempDGMBData.find((item: any) => {
                  return item === el.DGMB;
                });
                if (!resFindDG) {
                  el.DGMB = '';
                }
              } else {
                el.DGMB = tempDGMBData[0];
              }

              if (el.AuditReportTemplate) {
                const resFindAudit = tempTEMPLET.find((item: any) => {
                  return item.displayName === el.AuditReportTemplate;
                });
                if (!resFindAudit) {
                  //
                  el.AuditReportTemplate = '';
                  el.reportType = '';
                } else {
                  if (tempTEMPLET?.length) {
                    el.reportType = tempTEMPLET.filter(
                      (a: any) => a.displayName === el.AuditReportTemplate,
                    )[0].reportType;
                  } else {
                    el.reportType = '';
                  }
                }
              } else {
                if (tempTEMPLET?.length) {
                  el.AuditReportTemplate = tempTEMPLET[0].displayName; // 默认第1个
                  el.reportType = tempTEMPLET[0].reportType;
                } else {
                  el.AuditReportTemplate = ''; // 默认第1个
                  el.reportType = '';
                }
              }
              return el;
            },
          );
          setZcbfInitData(zcbfData);
        }
      } else {
        notify({ message: zcbfRes.data, position: 'top center' }, 'error', 2000);
      }
      setSpinLoad(false);
    },
    [],
  );

  useImperativeHandle(ref, () => ({
    showInit: async (zcbfIDs: string, initType: string) => {
      await getDataGrid({
        TEMPLETList: 'pm.TEMPLETList',
        CWBBTXList: 'pm.CWBBTXList',
        mbTypeList: 'pm.mbTypeList',
        zcbfIDs,
      });
      setProgressPercent(0);
      setInItVisible(true);
      setXmInitType(initType);
    },
  }));

  const judgmentStatus = (judgmentData: any) => {
    let dataRule: any[] = [];

    judgmentData.forEach((val: any) => {
      if (!val.TXCode || !val.TXName) {
        dataRule.push('财务报告体系');
      }
      if (!val.DGMB) {
        dataRule.push('底稿模板');
      }
      if (!val.AuditReportTemplate) {
        dataRule.push('报告模板');
      }
    });
    var newDataRule = [...new Set(dataRule)];
    return newDataRule;
  };

  const returnPeriod = async (tempParams: any, isLast: boolean = true) => {
    const resPer = await updateZcbfPeriod(tempParams);
    if (resPer.success) {
      if (isLast) {
        getPeriodInfo({ dbname: tempParams.dbName, reportType: tempParams.reportType });
      }
      return `${tempParams.dbName} 成功`;
    }
    return `${tempParams.dbName} 失败`;
  };

  // 最后更新Period_string的表
  const updatePeriod = async (element: any) => {
    let retrunStr = [];
    const resPer = await getPeriodList({
      zcbfID: element.zcbfid,
      dbName: element.projectDBName,
    });

    let tempParams: any = {
      ADateS: element.xmqjs,
      ADateE: element.xmqje,
      Data_ID: element.sjnd,
      dbName: element.zcbfid,
      reportType: element.reportType,
    };
    if (resPer.success) {
      if (resPer.data?.length) {
        const resPerLen = resPer.data.length - 1;
        retrunStr = resPer.data.map(async (els: any, index: number) => {
          let moothStr = '';
          let tempOBJ = { ...els, dbName: element.zcbfid, reportType: element.reportType };
          if (!els?.sjnd) {
            moothStr = getMomentMonthSjnd(element.xmqjs, element.xmqje);
            tempOBJ = { ...tempOBJ, sjnd: moothStr };
          }
          const retrunPerStr = await returnPeriod(tempOBJ, index == resPerLen);
          return retrunPerStr;
        });
        return retrunStr;
      } else {
        let moothStr = '';
        moothStr = getMomentMonthSjnd(element.xmqjs, element.xmqje);
        tempParams = { ...tempParams, sjnd: moothStr };
        const retrunPerStr = await returnPeriod(tempParams);
        return [retrunPerStr];
      }
    } else {
      let moothStr = '';
      moothStr = getMomentMonthSjnd(element.xmqjs, element.xmqje);
      tempParams = { ...tempParams, sjnd: moothStr };
      const retrunPerStr = await returnPeriod(tempParams);
      return [retrunPerStr];
    }
  };

  const saveZcbfInit = async (zcbfData: any[], onlineZcbfData: any[]) => {
    let Init: any[] = [];
    let Update: any[] = [];
    let interPeriod: string[] = [];

    setSpinLoad(true);
    for (let index = 0; index < zcbfData.length; index++) {
      const element = zcbfData[index];
      const tempData = {
        DGMB: element.DGMB,
        HyCode: element.HyCode,
        TXCode: element.TXCode,
        TXName: element.TXName,
        risklevel: element.risklevel,
        AuditReportDate: element.AuditReportDate,
        ReceivePerson: element.ReceivePerson,
        AuditReportTemplate: element.AuditReportTemplate,
        reportType: element.reportType,
      };
      const resZcbf = await getUpdateZcbf(tempData, { zcbfid: element.zcbfid });
      if (resZcbf.success) {
        Init.push({ success: true, data: 'ok' });
        const resInit = await getZcbfInit({ zcbfid: element.zcbfid, DGMB: element.DGMB });
        if (resInit.success) {
          Update.push({ success: true, data: 'ok' });
          // 删除本地存储信息
          removeLocalStorageItem(element.zcbfid);
          debugger;
          const resPeriod = await updatePeriod(element);
          interPeriod = interPeriod.concat(resPeriod);
          const floorNumber = Math.floor((Update.length / zcbfData.length) * 100);
          setProgressPercent(floorNumber);
        } else {
          Update.push({ success: false, data: `【${element.zcbfid}】${element.zcbfName}` });
        }
      } else {
        notify(
          { message: `初始化失败！${resZcbf.data}`, position: 'top center', width: 300 },
          'error',
          1000,
        );
        Init.push({ success: false, data: `【${element.zcbfid}】${element.zcbfName}` });
      }
    }
    const InitData = Init.filter((el: any) => {
      return !el.success;
    });
    const UpdateData = Update.filter((el: any) => {
      return !el.success;
    });
    const errorInit =
      InitData.length > 0 ? InitData.map((el) => el.data).join(',') + '初始化失败！' : '';
    const errorUpdate =
      UpdateData.length > 0 ? UpdateData.map((el) => el.data).join(',') + '更新失败！' : '';

    if (InitData.length === 0 && UpdateData.length === 0) {
      notify({ message: `初始化成功！`, position: 'top center' }, 'success', 3000);
    } else {
      notify({ message: `${errorInit}${errorUpdate}`, width: 300 }, 'error', 3000);
    }
    const lastPerID = Array.from(new Set(interPeriod));
    if (lastPerID.length >= zcbfData.length) {
      setInItVisible(false);
      setSpinLoad(false);
    }

    if (xmInitType === '联机审计项目') {
      // 更改 在线的组成部分信息
      try {
        const onlineRes = await pushZcbfInfoSQL(onlineZcbfData);
        if (!onlineRes.success) {
          notify({ message: `云平台 组成部分信息更改失败！`, width: 300 }, 'error', 3000);
        }
      } catch (error) {
        notify({ message: `云平台 组成部分信息更改失败！`, width: 300 }, 'error', 3000);
      }
    }
  };

  const saveData = (listData: any) => {
    debugger;
    initDataGridRef.current.instance.saveEditData().then(() => {
      listData.forEach(
        (el: {
          HyCode: string;
          TXCode: string;
          TXName: string;
          AuditReportTemplate: string;
          AuditReportDate: string;
        }) => {
          // const resHy = HyData.filter((val: { MBCode: string; }) => {
          //   return val.MBCode === el.HyCode;
          // })
          const resTx = TXData.filter((val: { TXCode: string }) => {
            return val.TXCode === el.TXCode;
          });
          if (resTx.length !== 0) {
            el.TXName = resTx[0].TXName;
          }
          if (el.AuditReportDate) {
            el.AuditReportDate = moment(el.AuditReportDate).format('YYYY-MM-DD');
          }
          return el;
        },
      );
      const onlineZcbfAllData = listData.map((el: any) => {
        const element = {
          TXCode: el.TXCode,
          TXName: el.TXName,
          DGMB: el.DGMB,
          AuditReportTemplate: el.AuditReportTemplate,
          AuditReportDate: el.AuditReportDate,
          ReceivePerson: el.ReceivePerson,
          zcbfID: el.zcbfid,
        };
        return element;
      });
      const calculationRule = judgmentStatus(listData);
      if (calculationRule.length === 0) {
        saveZcbfInit(listData, onlineZcbfAllData);
      } else {
        notify(
          { message: `请先补全[${calculationRule.join(',')}]列表并保存`, position: 'top center' },
          'warning',
          2000,
        );
      }
    });
  };
  const closeDialog = () => {
    setInItVisible(false);
    setZcbfInitData([]);
    closeAndReload();
    if (popupTitle === 'project') {
      PubSub.publish('projectTreeRefresh', { msg: 'projectRefresh' });
      PubSub.publish('zcbfidsTreeRefresh', { msg: 'zcbfidsRefresh' });
    }
  };
  const selectColumnName = (e: any) => {
    setselectColItem(e.column ? e.column.name : '');
    setselectRowItem(e.key);
  };

  // 默认展示单选

  const changeReport = () => {
    initDataGridRef.current.instance.saveEditData().then(() => {
      // 填充规则，已经知道选择是哪个列，和哪个行
      if (
        ['DGMB', 'AuditReportTemplate', 'TXCode', 'AuditReportDate'].includes(selectColItem) &&
        selectRowItem
      ) {
        const newarry = zcbfInitData.map((a: any) => {
          return {
            ...a,
            [selectColItem]: zcbfInitData.filter(
              (e: { zcbfid: string }) => e.zcbfid === selectRowItem,
            )[0][selectColItem],
            TXName: zcbfInitData.filter((e: any) => e.zcbfid === selectRowItem)[0].TXName,
            reportType: zcbfInitData.filter((e: any) => e.zcbfid === selectRowItem)[0].reportType,
          };
        });
        setZcbfInitData(newarry);
      } else {
        notify('未选中批量填充的列', 'warning');
      }
    });
  };
  return (
    <ProDialog
      ref={ref}
      visible={inItVisible}
      title="初始化组成部分"
      width={1300}
      height={600}
      {...props}
      onOK={() => {
        saveData(zcbfInitData);
      }}
      hideOnOutsideClick={true}
      onHiding={() => {
        closeDialog();
      }}
      onCancel={() => {
        closeDialog();
      }}
    >
      {spinLoad && <SpinLoading></SpinLoading>}
      {spinLoad && (
        <div
          style={{
            width: 300,
            position: 'absolute',
            bottom: 30,
            left: 25,
          }}
        >
          <Progress percent={progressPercent} status="active" />
        </div>
      )}
      <DataGrid
        height={`calc(100% )`}
        width={`calc(100% )`}
        dataSource={zcbfInitData}
        autoExpandAll={true}
        columnMinWidth={100}
        showBorders={true}
        ref={initDataGridRef}
        columnResizingMode="widget"
        keyExpr="zcbfid"
        showRowLines={true}
        allowColumnResizing={true}
        onEditingStart={selectColumnName}
        editing={{
          mode: 'cell',
          allowUpdating: true,
        }}
        scrolling={{ rowRenderingMode: 'virtual' }}
        loadPanel={{ enabled: true }}
        searchPanel={{ width: 220, visible: true, placeholder: '' }}
        toolbar={
          zcbfInitData.length >= 2
            ? {
                items: [
                  {
                    location: 'after',
                    widget: 'dxButton',
                    name: 's',
                    options: {
                      text: '批量填充',
                      onClick() {
                        changeReport();
                      },
                      stylingMode: 'outlined',
                    },
                  },
                  {
                    name: 'searchPanel',
                    location: 'after',
                  },
                ],
              }
            : {}
        }
      >
        {zcbfInitData.length >= 2 && (
          <Column caption="组成部分名称" dataField="zcbfName" width={180} allowEditing={false} />
        )}
        <Selection mode="single" />

        <Column caption="被审计单位名称" dataField="bsdw" width={180} allowEditing={false} />
        <Column caption="简称" dataField="ShortName" width={180} allowEditing={false} />
        <Column
          caption="底稿模板"
          // allowEditing={true}
          dataField="DGMB"
          lookup={{
            dataSource: DGMBData,
            searchEnabled: true,
          }}
          editorOptions={{
            dropDownOptions: {
              height: 200,
              width: 300,
            },
          }}
        ></Column>
        <Column
          caption="财务报告体系"
          dataField="TXCode"
          // visible={oneSetTXCode}
          lookup={{
            dataSource: TXData,
            displayExpr: 'TXName',
            valueExpr: 'TXCode',
          }}
          editorOptions={{
            dropDownOptions: {
              height: 200,
              width: 300,
            },
          }}
        ></Column>
        <Column
          caption="报告模板"
          dataField="AuditReportTemplate"
          lookup={{
            dataSource: TEMPLETData,
            searchEnabled: true,
            valueExpr: 'displayName',
            displayExpr: 'displayName',
          }}
          editorOptions={{
            dropDownOptions: {
              height: 200,
              width: 300,
            },
            onItemClick: async (e: any) => {
              debugger;
              const nextCounters = zcbfInitData.map((c: any) => {
                if (selectRowItem === c.zcbfid) {
                  return {
                    ...c,
                    reportType: e.itemData.reportType,
                    AuditReportTemplate: e.itemData.displayName,
                  };
                } else {
                  return { ...c };
                }
              });
              setZcbfInitData(nextCounters);
              // setFormAllData();
            },
          }}
        ></Column>
        <Column caption="收件人" dataField="ReceivePerson"></Column>
        <Column caption="报告批准报出日期" dataField="AuditReportDate" dataType="date"></Column>
      </DataGrid>
    </ProDialog>
  );
});

export default InitializePopup;
